﻿using RAP.Framework.Libary.DataSource;
using RAP.Web.Libary.Service;
using RAP.Web.Libary.Service.Attributes;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using RAP.Web.Libary.Common;
using RAP.Web.Core.Server.Model.Test;
using RAP.Framework.Libary.SqlDataService.Service;
using RAP.Web.Libary.Common.Model;
using RAP.Framework.Libary.DataSource.Model;
using RAP.Framework.Libary.DataSource.Context;

namespace RAP.Web.Core.Server.Service.Test
{
  /// <summary>
  /// 
  /// </summary>
  [ServiceScope( ScopeType = ServiceScopeTypes.Transient )]
  public class TestService : APIServiceBase
  {
    public TestService( IServiceProvider serviceProvider ) : base( serviceProvider ) { }

    public async Task<object> TestLazyLoadQuery( IQueryParams queryParam )
    {
      var result = await this.SqlDataService.ExecuteNoCache( queryParam );
      if ( result.HasError )
      {
        return result.Error;
      }
      //使用Task来解决属性懒加载同步执行的问题，可防止线程被阻塞
      return await Task.Run<object>( async ( ) =>
      {
        var cities = result.Data.Citys as IList<City>;
        foreach ( var city in cities )
        {
          foreach ( var school in city.Schools )
          {
            foreach ( var @class in school.Classes )
            {
              var teacher = @class.Teacher;
              var assistant = @class.Assistant;
              Console.WriteLine( $"Teacher:{teacher.Name}, Assistant:{assistant.Name}" );
              foreach ( var student in @class.Students )
              {
                await student.GetCourses();
                Console.WriteLine( $"Student:{student.Name}" );
              }
            }
          }
        }
        return cities;
      } );
    }

    public async Task<object> TestDynamic( IQueryParams queryParam )
    {
      return await this.SqlDataService.ExecuteNoCache( queryParam );
    }

    public async Task<object> TestIfElse( IQueryParams queryParam )
    {
      return await this.SqlDataService.ExecuteNoCache( queryParam );
    }

    public async Task<object> TestScript( IQueryParams queryParam )
    {
      return await SqlDataService.ExecuteNoCache( queryParam );
    }

    public async Task<object> TestRunExpression( IQueryParams queryParam )
    {
      return await SqlDataService.ExecuteNoCache( queryParam );
    }

    public async Task<object> Test_Related_Query( IQueryParams queryParam )
    {
      return await SqlDataService.ExecuteNoCache( queryParam );
    }

    public async Task<object> TestAttrs(IQueryParams queryParam)
    {
      return await SqlDataService.ExecuteNoCache(queryParam);
    }
  }
}
